package com.euphoric.version.ant.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.tools.ant.BuildException;

import com.euphoric.version.Version;

public class SourceWriter {
	private SourceWriter() {}
	
	public static void create(File file, VersionFactory version, String className, String packageName) {
		
		try {
			Version vinfo = new Version();
			
			file.delete();
			file.createNewFile();
			
			BufferedReader reader = null;
			InputStream stream = null;
			
			try {
				stream = SourceWriter.class.getResourceAsStream("com/dsp/version/ant/util/template.txt");
				reader = new BufferedReader(new InputStreamReader(stream));
			} catch (Exception ex) {
				stream = SourceWriter.class.getResourceAsStream("template.txt");
				reader = new BufferedReader(new InputStreamReader(stream));
			}
			
			StringBuffer buffer = new StringBuffer();
			String line;
			while((line = reader.readLine()) != null) {
				buffer.append(line + "\n");
			}
			reader.close();
			stream.close();
			
			String template = buffer.toString();
			template = template.replace("${class}", className);
			template = template.replace("${package}", packageName);
			template = template.replace("${versioninfo}", vinfo.getFullVersion());
			template = template.replace("${major}", String.valueOf(version.getMajorVersion()));
			template = template.replace("${minor}", String.valueOf(version.getMinorVersion()));
			template = template.replace("${rev}", String.valueOf(version.getRevision()));
			template = template.replace("${build}", String.valueOf(version.getBuildNumber()));
			template = template.replace("${serial}", String.valueOf(version.serial));
			template = template.replace("${name}", version.getName());
			
			FileWriter writer = new FileWriter(file);
			writer.write(template);
			writer.flush();
			writer.close();
			
			System.out.print("Version Info :: " + version.getName() + " " + version.getFullVersion());
			
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new BuildException("Update Failed");
		}
	}
}
